package controllers.games;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JButton;

import models.games.ColoriEParole;
import views.games.ColoriEParoleView;
import core.GameLauncher;
import core.GameLauncher.State;

public class ColoriEParoleController extends KeyAdapter implements
		ActionListener {

	private ColoriEParole model;
	private ColoriEParoleView view;
	private int gameCount;
	private GameLauncher gameLauncher;

	public ColoriEParoleController(ColoriEParole model, ColoriEParoleView view,
			GameLauncher gameLauncher) {
		this.model = model;
		this.view = view;
		this.gameLauncher = gameLauncher;

		view.addActionListenerToGame(this);
		view.addKeyListenerToGame(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		gameCount++;
		if (gameCount == 4) {
			model.randomize();
			view.randomize(model.casualStringColor(), model.getColorMeaning(),
					model.getColoredWord());
			gameCount = 0;
		}
		JButton input = (JButton) e.getSource();
		String inputText = input.getText();
		if (inputText.equals("Ricomincia")) {
			ColoriEParole newModel = new ColoriEParole(model.getCurrentUser());
			ColoriEParoleView newView = new ColoriEParoleView(
					newModel.casualStringColor(), newModel.getColorMeaning(),
					newModel.getColoredWord());
			ColoriEParoleController newController = new ColoriEParoleController(
					newModel, newView, gameLauncher);
			gameLauncher.setGame(newModel, newView, newController);
			gameLauncher.startTransition(State.GAME);
			model.addGameToDatabase();
			System.out.println("Ricomincia");
		} else if (inputText.equals("Menu Giochi")) {
			gameLauncher.startTransition(State.GAME_MENU);
			model.addGameToDatabase();
			System.out.println("Menu Giochi");
		} else if (model.verify(inputText, view.getGameIndex())) {
			System.out.println("CORRETTO");
			gameLauncher.correctAnswer();
			view.setScore(model.getScore());
			// gameLauncher.incrementExperience();
		}
		view.refresh(model.casualStringColor(), model.getGameCount());
	}

	@Override
	public void keyPressed(KeyEvent e) {
		gameCount++;
		if (gameCount == 4) {
			model.randomize();
			view.randomize(model.casualStringColor(), model.getColorMeaning(),
					model.getColoredWord());
			gameCount = 0;
		}
		String inputText = "";
		if (e.getKeyCode() == KeyEvent.VK_RIGHT)
			inputText = "SI";
		if (e.getKeyCode() == KeyEvent.VK_LEFT)
			inputText = "NO";
		System.out.println("ASCOLTATO " + inputText);
		if (model.verify(inputText, view.getGameIndex())) {
			gameLauncher.correctAnswer();
			view.setScore(model.getScore());
			// gameLauncher.incrementExperience();
		}
		view.refresh(model.casualStringColor(), model.getGameCount());
	}

}
